<template>
  <!-- App -->
  <f7-app :params="f7params">

    <!-- Statusbar -->
    <f7-statusbar></f7-statusbar>

    <!-- Left Panel -->
    <f7-panel left reveal theme-dark>
      <f7-view url="/panel-left/"></f7-view>
    </f7-panel>

    <!-- Right Panel -->
    <f7-panel right reveal theme-dark>
      <f7-view url="/panel-right/"></f7-view>
    </f7-panel>

    <!-- Main View -->
    <f7-view id="main-view" url="/" main class="safe-areas"></f7-view>

    <!-- Login Screen -->
    <f7-login-screen id="login-screen" :opened="loginScreenOpened">
      <f7-view>
        <f7-page login-screen>
          <f7-login-screen-title>Login</f7-login-screen-title>
          <f7-list form>
            <f7-list-input
              label="用户名"
              name="username"
              placeholder="请输入用户名"
              type="text"
              :value="username"
              @input="username = $event.target.value"
            />
            <f7-list-input
              label="密码"
              name="password"
              type="password"
              placeholder="请输入密码"
              :value="password"
              @input="password = $event.target.value"
            />
          </f7-list>
          <f7-list>
            <f7-list-button title="登录" @click="signIn"></f7-list-button>
          </f7-list>
        </f7-page>
      </f7-view>
    </f7-login-screen>

  </f7-app>
</template>

<script>
  import Login from './api/login'
  import {logoutUrl, applicationURL} from './config/global.toml'
  import Vue from 'vue'
  import {mapMutations} from 'vuex'
  // Import Routes
  import routes from './routes.js'

  export default {
    data() {
      return {
        // Framework7 parameters here
        f7params: {
          id: 'io.framework7.testapp', // App bundle ID
          name: 'Framework7', // App name
          theme: 'auto', // Automatic theme detection
          // App routes
          routes: routes,
          dialog: {
            buttonOk: '确定',
            buttonCancel: '取消'
          }
        },
        loginScreenOpened: true,
        username: '',
        password: ''
      }
    },
    mounted() {
    },
    created() {
      this.$f7ready(f7 => {
        window.MyApp$f7 = this.$f7
        Vue.prototype.$AppF7 = this.$f7
      })
    },
    mounted() {
      let _username = this.$KalixCatch.get('loginname')
      if (_username) {
        this.loginScreenOpened = false
      }
    },
    methods: {
      ...mapMutations({
        setAppF7: 'setAppF7',
        setCurrentUser: 'setCurrentUser',
        setMenuList: 'setMenuList',
        setNavigateTreeData: 'setNavigateTreeData'
      }),
      signIn() {
        Login.remoteLogin({
          'username': this.username,
          'password': this.password
        }).then(data => {
          console.log('data', data)
          if (data.success) {
            this.$KalixCatch.save('id', data.user.id)
            this.$KalixCatch.save('access_token', data.access_token)
            this.$KalixCatch.save('user_token', data.user.token)
            this.$KalixCatch.save('user_name', data.user.name)
            this.$KalixCatch.save('loginname', this.username)
            // 在缓存中记录最后登录时间，处理单用户登录需求
            let now = new Date().getTime()
            this.$KalixCatch._saveLocal('lastLoginTime', now)
            this.$KalixCatch.save('lastLoginTime', now)
            data.user.loginname = this.username
            this.setCurrentUser(data.user)
            this._getMenu(() => {
              this.$f7.loginScreen.close()
            })
          } else {
            let toastCenter = this.$f7.toast.create({
              text: '账号或密码错误',
              position: 'center',
              closeTimeout: 2000,
            });
            toastCenter.open()
          }
        })
      },
      _getMenu(callBack) {
        this.treeListData = {}
        this.menu = []
        this.$http.get(applicationURL, {
          params: {
            _dc: (new Date()).getTime(),
            page: 1,
            start: 0,
            limit: 25
          }
        }).then(res => {
          if (res && res.data) {
            console.log('[res] data:', res.data)
            this.menu = res.data
            this.setMenuList(this.menu)
            this.setList(0, () => {
              console.log(this.treeListData)
              this.setNavigateTreeData(this.treeListData)
              callBack()
            })
          }
        })
      },
      setList(index, callBack) {
        if (index < this.menu.length) {
          let item = this.menu[index]
          let key = item.id
          let _treeData = []
          this.$http.get(`${applicationURL}/${key}`,
            {
              params: {
                _dc: (new Date()).getTime(),
                node: 'root'
              }
            })
            .then(res => {
              if (res.data && res.data.code !== 401) {
                _treeData = res.data
                _treeData.map(e => {
                  this.$set(e, 'isShow', false)
                })
                console.log('this.treeListData[key]', key)
                this.treeListData[key] = _treeData
                this.setList(index += 1, callBack)
              }
            })
        } else {
          callBack()
        }

      }
    }
  }
</script>
